#!/bin/bash

# 网络层测试脚本

set -e

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
BLUE='\033[0;34m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

echo -e "${BLUE}==>${NC} ${GREEN}网络层测试${NC}"

# 读取配置
N=$(jq -r '.n_nodes' etc/conf.json)
echo -e "${GREEN}[INFO]${NC} 节点数: N=$N"

# 清理
echo -e "${BLUE}==>${NC} ${GREEN}清理进程和日志...${NC}"
pkill -f test_network || true
rm -rf logs_network
mkdir -p logs_network
sleep 1

# 编译
echo -e "${BLUE}==>${NC} ${GREEN}编译网络测试...${NC}"
go build -o test_network test_network.go
if [ $? -ne 0 ]; then
    echo -e "${RED}[ERROR]${NC} 编译失败"
    exit 1
fi
echo -e "${GREEN}[INFO]${NC} 编译成功"

# 启动所有节点
echo -e "${BLUE}==>${NC} ${GREEN}启动 $N 个节点进行网络测试...${NC}"
for i in $(seq 0 $((N-1))); do
    ./test_network $i > logs_network/node_$i.log 2>&1 &
    echo -e "${GREEN}[INFO]${NC} 启动节点 $i (PID: $!)"
done

# 等待测试完成
echo -e "${BLUE}==>${NC} ${GREEN}等待测试完成 (15秒)...${NC}"
sleep 15

# 收集结果
echo -e "\n${BLUE}==>${NC} ${GREEN}测试结果汇总${NC}"
echo -e "${YELLOW}================================${NC}"

for i in $(seq 0 $((N-1))); do
    echo -e "\n${BLUE}=== 节点 $i 结果 ===${NC}"
    
    # 检查连接建立
    if grep -q "Full network connection established" logs_network/node_$i.log; then
        echo -e "${GREEN}✅ 网络连接已建立${NC}"
    else
        echo -e "${RED}❌ 网络连接未建立${NC}"
    fi
    
    # 检查测试结果
    if grep -q "Network test PASSED" logs_network/node_$i.log; then
        echo -e "${GREEN}✅ 网络测试通过${NC}"
    else
        echo -e "${RED}❌ 网络测试失败${NC}"
    fi
    
    # 显示摘要
    echo -e "${BLUE}消息接收统计:${NC}"
    grep "From Node" logs_network/node_$i.log | tail -$N || true
    grep "From self" logs_network/node_$i.log || true
done

echo -e "\n${YELLOW}================================${NC}"

# 清理
echo -e "${BLUE}==>${NC} ${GREEN}清理进程...${NC}"
pkill -f test_network || true

echo -e "${GREEN}[INFO]${NC} 网络测试完成"
echo -e "${BLUE}详细日志位于: logs_network/${NC}"

